package com.atguigu.gmall.order.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;

/**
 * @author dyqstart
 * @create 2021-08-20-23:32
 * @since 1.0.0
 */
@Component
public class OrderServiceImpl implements OrderService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean checkToken(String userId,String tradeNo) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        //原子验；令牌
        //令牌用完就删，防止恶意重试
//        String token = operations.get(RedisConst.USER_UNREPEAT_TOKEN + userId);
//        redisTemplate.delete(RedisConst.USER_UNREPEAT_TOKEN+userId);

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] " +
                "then return redis.call('del', KEYS[1]) else return 0 end";

        Long execute = redisTemplate.execute(
                new DefaultRedisScript<Long>(script,Long.class),
                Arrays.asList(RedisConst.USER_UNREPEAT_TOKEN + userId),
                tradeNo);

        //前端 带请求进来，拿到令牌后立刻将其删除
        if (!StringUtils.isEmpty(tradeNo) && execute.longValue() != 0L){
            //验令牌成功

            return true;
        }
        return false;
    }
}
